package com.yyl.fmall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.yyl.fmall.user.entity.User;
import com.yyl.fmall.user.exception.IllegalCharacterException;
import com.yyl.fmall.user.mapper.UserMapper;
import com.yyl.fmall.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyl.fmall.user.shiro.ShiroConstants;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author YuanSir
 * @since 2022-11-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User regist(User user) {
        
        //1.比对密码是否一致
        String password = user.getPassword();
        String repassword = user.getRepassword();
        if (!(password != null && password.equals(repassword))) {
            
            //密码有问题，两次密码不一致
            throw new IllegalCharacterException("密码有问题，两次密码不一致！");
            
        }
        
        //2.检查用户名是否存在
        User dbUser = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (dbUser != null){
            
            throw new IllegalCharacterException("用户名已存在！");
            
        }
    
        //3.生成salt，对密码进行加密处理
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String shiroPassword = new Md5Hash(password, salt, ShiroConstants.HASH_ITERATIONS).toHex();
    
        //4.保存用户数据到数据库
        user.setSalt(salt);
        user.setPassword(shiroPassword);
        user.setUserRegtime(new Date());
        user.setUserModtime(new Date());
        save(user);
        
        return user;
        
        
    }
}
